package com.example.jdbc.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import com.example.jdbc.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.stereotype.Service;

import com.example.jdbc.bean.LearnResource;
import com.example.jdbc.bean.UserRowMapper;

@Service
public class userDaoImple implements userDao {
    @Autowired
    JdbcTemplate jdbcTemplate;


    public List<LearnResource> listAllUser() {
        List<LearnResource> list = jdbcTemplate.query("select * from user", new UserRowMapper());
        return list;
    }

    public int insertUser(final LearnResource user) {
       return jdbcTemplate.update("insert into user (id,author,title,url) VALUES (?,?,?,?)", new PreparedStatementSetter() {
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setInt(1,user.getId());
                ps.setString(2,user.getAuthor());
                ps.setString(3,user.getTitle());
                ps.setString(4, user.getUrl());
            }
        });

    }

    public int updateUser(final LearnResource user) {
        int result = jdbcTemplate.update("UPDATE user set author=?,title=?,url=? where id=?", new PreparedStatementSetter() {
            public void setValues(PreparedStatement ps) throws SQLException {
                ps.setString(1,user.getAuthor());
                ps.setString(2,user.getTitle());
                ps.setString(3,user.getUrl());
                ps.setInt(4,user.getId());
            }
        });

        return result;
    }

    public int deleteUser(int id) {
         return  jdbcTemplate.update("delete from user where id=?",new Object[]{id},new int[]{Types.INTEGER});

    }
    public LearnResource selectUser(int id){
//          (LearnResource) jdbcTemplate.queryForObject( "SELECT title FROM user WHERE id = ?", new Object[] {id}, java.lang.String.class);
        return (LearnResource)jdbcTemplate.queryForObject("SELECT title FROM user WHERE id = ?", new Object[] {id},new BeanPropertyRowMapper(LearnResource.class));
    }

    @Override
    public User selectUser(String title) {
        return (User)jdbcTemplate.queryForObject("SELECT * FROM USER WHERE TITLE=?",new Object[]{title},new BeanPropertyRowMapper(LearnResource.class));
    }
}
